package com.zyt.i18n.document;

import com.sun.tools.internal.xjc.Language;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * . <p/> @author <a href="mailto:oznyang@163.com">oznyang</a> @version V1.0, 2009-7-14 17:57:28
 */
public class I18nTool {

    private static final String ENCODING = "UTF-8";
    private static final String I18N_ENCODING = "UTF-8";
    public static final int BUFF_SIZE = 10240;
    private static final Pattern CHINESE_PATTERN = Pattern.compile("[ \\w\\ufe30-\\uffa0\\u4e00-\\u9fa5]*[\\u4e00-\\u9fa5]+[ \\w\\ufe30-\\uffa0\\u4e00-\\u9fa5]*");

    //private String PROP_NAME = "i18n_chinese.properties";
    //private String OUT_FILE = "i18n_other.properties";
    private static String propName = "";
    private static String propChineseName = "";
    private static String outFile = "";

    public static void printUsage() {
        System.out.println("Usage: I18nTool -type path [appName]");
        System.out.println("I18nTool V1.0 by oznyang");
        System.out.println("    type：-get|-put");
        System.out.println("    get: export chinese word to i18n.properties file");
        System.out.println("    put: import i18n.properties config to jsps");
    }

    public static void putChinereWord(String path, String appName, String toLanguage) {

        propChineseName = path + "zh_cn.js";
        List<File> files = new ArrayList<File>();
        getJsps(new File(path), files);
        Map<String, String> i18nMap = loadI18nMap(propChineseName);
        for (File file : files) {
            String content = file2String(file, ENCODING);
            Matcher m = CHINESE_PATTERN.matcher(content);
            StringBuffer sb = new StringBuffer();
            while (m.find()) {
                String key = i18nMap.get(m.group().trim());
                m.appendReplacement(sb, key == null ? m.group() : getI18nString(key));
            }
            m.appendTail(sb);
            //替换页面中的中文
            //string2File(sb.toString(), file);
        }
        outFile = toLanguage + ".js";
        saveI18nMap(i18nMap, path + outFile, toLanguage);
    }

    private static void saveI18nMap(Map<String, String> map, String path, String toLanguage) {
        String language = "";
        if (toLanguage != null && toLanguage != ""){
            String[] languages = toLanguage.split("_");
            if (languages.length > 0){
                language = languages[0];
            }
        }
        Properties ps = new Properties();
        try {
            Writer osw = new OutputStreamWriter(new FileOutputStream(path), I18N_ENCODING);
            osw.write("const "+toLanguage+" = { \n");
            for (Map.Entry<String, String> entry : map.entrySet()) {

                System.out.print("中文翻译成  " + toLanguage + "   语言:" + entry.getValue() + "-->");
                String translatedText = BaiduFanYi.chineseFanYi(entry.getKey(), "zh", language);
                System.out.println(translatedText + "");

                osw.write("'"+entry.getValue()+ "' : '" + translatedText + "', \n");
            }
            osw.write("} \n export default "+toLanguage);
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, String> loadI18nMap(String path) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new File(path)));
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                if (line.contains(":")){
                    String[] ss = line.split(":");
                    String key = ss[0].replace("'","");
                    String value = ss[1].replace("'","");

                    if (key != null && key != "") {
                        String key1 = key.replace(",","").trim();
                        String value1 = value.replace(",","").trim();
                        map.put(value1, key1);
                    }
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private static String getI18nString(String str) {
        return "<spring:message code=\"" + str + "\"/>";
    }

    public static void getChinereWord(String path, String appName) {
        List<File> files = new ArrayList<File>();
        getJsps(new File(path), files);
        Map<String, String> map = new HashMap<String, String>();
        for (File file : files) {
            String content = file2String(file, "utf-8");
            Matcher ma = CHINESE_PATTERN.matcher(content);
            System.out.println("-------" + file.getPath() + "-------");
            while (ma.find()) {
                System.out.println(ma.group().trim());
                map.put(ma.group().trim(), appName);
            }
        }
        try {
            System.out.println("-------begin translate-------");
            propName = "zh_cn.js";
            Writer osw = new OutputStreamWriter(new FileOutputStream(path + propName), I18N_ENCODING);
            osw.write("const zh_CN = { \n");
            for (Map.Entry<String, String> entry : map.entrySet()) {

                System.out.print("  translate " + entry.getKey() + " -> ");
                String translatedTextEn = BaiduFanYi.chineseFanYi(entry.getKey(), "zh", "en");
                /*String translatedText = BaiduFanYi.chineseFanYi(entry.getKey(), Language.CHINESE_SIMPLIFIED.toString(), toanguage);

                translatedText = translatedText.toLowerCase().replaceAll(" ", ".");
                System.out.println(translatedText + "");*/
                System.out.println(translatedTextEn + "");
                String translatedTextEnUp = "";
                String[] strings = translatedTextEn.split("\\ ");
                if (strings.length > 0) {
                    for (String key : strings) {
                        // 得到每一个单词的第一个字母
                        String firstKey = String.valueOf(key.charAt(0));
                        // 将每一个首字母转成大写
                        String upKey = key.replaceFirst(firstKey, firstKey.toUpperCase());
                        translatedTextEnUp = translatedTextEnUp + upKey;
                    }
                }
                osw.write("'"+entry.getValue() + "." + translatedTextEnUp + "' : '" + entry.getKey() + "', \n");
            }
            osw.write("} \n export default zh_CN");
            osw.close();
            System.out.println("-------end translate-------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void getJsps(File path, List<File> fileList) {
        File[] files = path.listFiles();
        for (File file : files) {
            if (file.isDirectory() && !file.isHidden()) {
                getJsps(file, fileList);
            } else if (file.getName().toLowerCase().endsWith(".jsp") || file.getName().toLowerCase().endsWith(".html") ) {
                fileList.add(file);
            }
        }
    }

    public static String file2String(File file, String encoding) {

        StringWriter writer = new StringWriter();
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file), encoding);
            char[] buffer = new char[BUFF_SIZE];
            int n;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return writer.toString();
    }

    public static void string2File(String content, File file) {
        try {
            Writer osw = new OutputStreamWriter(new FileOutputStream(file), ENCODING);
            osw.write(content);
            osw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
